﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ControllerClient
{
    class DESHelper
    {
        #region 3des加密
        /// <summary>
        /// 3des CBC模式加密
        /// </summary>
        /// <param name="aStrString">待加密的字符串</param>
        /// <param name="aStrKey">密钥</param>
        /// <param name="iv">加密矢量：只有在CBC解密模式下才适用</param>
        /// <param name="mode">运算模式</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt3Des(string aStrString, string aStrKey, CipherMode mode = CipherMode.CBC, string iv = "0000000000000000")
        {
            string str = "11";
            byte[] ret = null;
            try
            {
                var des = new TripleDESCryptoServiceProvider
                {
                    Key = HexUtils.strToHexByte(aStrKey),
                    Mode = mode
                };
                if (mode == CipherMode.CBC)
                {
                    des.IV = HexUtils.strToHexByte(iv);
                }
                var desEncrypt = des.CreateEncryptor();
                Console.WriteLine("desEncrypt" + desEncrypt);
                byte[] buffer = HexUtils.strToHexByte(aStrString);
                ret = desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length);
                
               
            }
            catch (Exception e)
            {
               Console.WriteLine(e);
            }
            return HexUtils.byteToHexStr(ret);
        }
        #endregion
        #region 3des解密
        /// <summary>
        /// des 解密
        /// </summary>
        /// <param name="aStrString">加密的字符串</param>
        /// <param name="aStrKey">密钥</param>
        /// <param name="iv">解密矢量：只有在CBC解密模式下才适用</param>
        /// <param name="mode">运算模式</param>
        /// <returns>解密的字符串</returns>
        public static byte[] Decrypt3Des(string aStrString, string aStrKey, CipherMode mode = CipherMode.CBC, string iv = "0000000000000000")
        {
            try
            {
                var des = new TripleDESCryptoServiceProvider
                {
                    Key = HexUtils.strToHexByte(aStrKey),
                    Mode = mode,
                    Padding = PaddingMode.PKCS7
                };
                if (mode == CipherMode.CBC)
                {
                    des.IV = HexUtils.strToHexByte(iv);
                }
                var desDecrypt = des.CreateDecryptor();
                var result = "";
                byte[] buffer = HexUtils.strToHexByte(aStrString);
                byte[] ret = desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length);
                
                return ret;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        #endregion
    }
}
